from sklearn import svm
import tranpoint
import fetchdata
import cPickle
import show
import numpy as np
def calSameDirection(caloutput,targetoutput):
    o3 = caloutput * targetoutput
    sum=0
    for one in o3:
        if one>0:
            sum+=one
        else:
            sum-=abs(one*2)
    return sum/len(caloutput)
def Train(train_input, train_output, test_input, test_output,savefile,evaluation_func=calSameDirection):
    CSTEP=80
    GMSTEP=4e-5
    CSDOWN=1
    downcount=20
    def TrySVC(C,gamma,note):
        clf = svm.SVC(kernel='rbf', C=C, gamma=gamma)
        clf.fit(train_input,train_output)
        o1=clf.decision_function(test_input)
        error=evaluation_func(o1,test_output)
        return error,clf,C,gamma,note
    pt=TrySVC(200,1e-4,"0")
    passdic=None
    while True:
        dic=[]
        if passdic!="c+":
            dic.append(TrySVC(pt[2]+CSTEP,pt[3],"c+"))
        if passdic != "c-":
            dic.append(TrySVC(pt[2] - CSTEP, pt[3], "c-"))
        if passdic!="g+":
            dic.append(TrySVC(pt[2], pt[3]+GMSTEP, "g+"))
        if passdic!="g-":
            dic.append(TrySVC(pt[2], pt[3]-GMSTEP, "g-"))
        dic.sort(key=lambda one:one[0],reverse=True)
        if dic[0][0]>pt[0]:
            oldpt=pt
            pt=dic[0]

            print pt[0],pt[2],pt[3]
            if abs((oldpt[0]-pt[0])/oldpt[0])<0.01:
                clf=pt[1]
                break
            if dic[0][4]=="c+":
                passdic="c-"
            elif dic[0][4]=="c-":
                passdic = "c+"
            elif dic[0][4]=="g+":
                passdic = "g-"
            elif dic[0][4]=="g-":
                passdic = "g+"
        else:
            if CSDOWN:
                CSDOWN=0
                CSTEP = CSTEP/10
                downcount -= 1
                passdic = None
                print "CSDOWN"
            else:
                CSDOWN=1
                GMSTEP = GMSTEP/10
                downcount -= 1
                passdic = None
                print "GMDOWN"
            if downcount<0:
                clf=pt[1]
                print pt[0],pt[2],pt[3]
                break

    with open(savefile, 'wb') as fid:
        cPickle.dump(clf, fid)
def getone(one):
    return one["macd"][0],one["macd"][1],one["macd"][2], \
           one["sar"]-one["DI"],one["rsi"],one["bband"][0]-one["High"],one["bband"][2]-one["Low"], \
           one["stoch"][0],one["stoch"][1]
if __name__ == "__main__":
    datalist=fetchdata.loaddate("data/golddata.gz")
    tranpoint.findTranPoint(datalist[30:-100])
    srclist,reslist=tranpoint.fetchTranlist(datalist,getone)
    train_input,train_output,test_input,test_output=tranpoint.splitTrainTest(srclist,reslist)
    Train(train_input, train_output, test_input, test_output,"data/goldDI.svc")

    with open("data/goldDI.svc", 'rb') as fid:
        svc=cPickle.load(fid)
    def DrawIndex(ax,datalist):
        poslist=[one["pos"] for one in datalist]
        datacalc=[getone(one) for one in datalist]
        testdata = np.array(datacalc)
        disres = svc.decision_function(testdata)
        ax.plot(poslist, disres , color="r")
        ax.hlines(0, poslist[0], poslist[-1], colors='b')
        ax.hlines([10, 5, 0, -5, -10], poslist[0], poslist[-1], colors=['r', 'r', 'b', 'g', 'g'], linestyles='dashdot')
        return disres

    def exDrawLine(axs,datalist):
        DrawIndex(axs[1],datalist)
    show.Show(datalist,exDrawLine,500)
